package com.uit.gis.pojo;

import com.uit.gis.util.JsonData;
import com.uit.gis.util.Util.SpatialType;

import processing.data.JSONArray;
import processing.data.JSONObject;

public class Quad extends Shape {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	int clickCount = 0;
	JSONArray quad = new JSONArray();
	@Override
	public void setup()
	{
		spatialType = SpatialType.QUAD;
		background(255);
	}
	public void draw() {
		if (!continueDraw) {
			return;
		}
		background(255);
		stroke(0);
		noFill();

		beginShape();
		for (int i = 0; i < quad.size(); i++) {
			JSONObject vertex = quad.getJSONObject(i);
			vertex(vertex.getInt("x"), vertex.getInt("y"));
		}

		if (quad.size() > 0 && quad.size() < 4) {
			endShape();
			stroke(255);
			JSONObject vertex = quad.getJSONObject(quad.size() - 1);
			line(mouseX, mouseY, vertex.getInt("x"), vertex.getInt("y"));
		} else if (quad.size() == 4) {
			JSONObject vertex = quad.getJSONObject(0);
			vertex(vertex.getInt("x"), vertex.getInt("y"));
			endShape();
		}
	}

	public void mousePressed() {
		if (!continueDraw) {
			return;
		}
		if (clickCount <= 3) {
			clickCount++;
			JSONObject vertex = new JSONObject();
			vertex.setInt("x", mouseX);
			vertex.setInt("y", mouseY);
			quad.append(vertex);
		}
		// else {
		// quad = new JSONArray();
		// clickCount = 0;
		// }
	}

	@Override
	public void mouseClicked(processing.event.MouseEvent e) {

		if (e.getButton() == processing.core.PConstants.RIGHT
				&& clickCount == 4) {
			//saveJSONArray(quad, "quad.json");
			saveToTextFile();
			continueDraw = false;
		} else if (e.getButton() == processing.core.PConstants.LEFT
				&& clickCount == 4 && !continueDraw) {
			quad = new JSONArray();
			clickCount = 0;
			continueDraw = true; // resume
		}
	}

	@Override
	public void saveToTextFile() {
		// TODO Auto-generated method stub
		saveJSONArray(quad, getSavingPath());
		super.saveToTextFile();
	};
	// void keyPressed() {
	// if (quad.size() == 4) {
	// saveJSONArray(quad, "quad.json");
	// exit();
	// }
	// }
	@Override
	public JsonData loadDataFromFile() {
		// TODO Auto-generated method stub
		JSONArray jsonArray = loadJSONArray(getSavingPath());
		JsonData jsonData = new JsonData(jsonArray, null);
		return jsonData;
	};

}
